package cn.dengqiang.user.controller;

import cn.dengqiang.basic.exception.BusinessException;
import cn.dengqiang.basic.util.AjaxResult;
import cn.dengqiang.basic.util.PageList;
import cn.dengqiang.user.domain.User;
import cn.dengqiang.user.dto.UserDto;
import cn.dengqiang.user.query.UserQuery;
import cn.dengqiang.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController   //=@ResponseBody+@Controller
@RequestMapping("/user")

@Api(tags = "用户接口",description = "店铺接口详细描述")
public class UserController {

    @Autowired
    private IUserService userService;

    @PutMapping
    public AjaxResult save(@RequestBody User user){
        try {
            if (user.getId()==null){
                userService.add(user);
            }else {
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存失败"+e.getMessage());
        }
    }




    @ApiOperation(value = "删除",notes = "根据id删除一条数据")
    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            userService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
           return new AjaxResult("删除失败!"+e.getMessage());
       }
    }

    @ApiOperation(value = "查询",notes = "根据id查询一条数据")
    @GetMapping("/{id}") //根据id查询
    public User getById(@PathVariable("id") Long id){
        return userService.getById(id);
    }

    @ApiOperation(value = "查询",notes = "查询所有信息")
    @GetMapping //user 查询所有
    public List<User> getAll(){
        return userService.getAll();
    }

    @ApiOperation(value = "查询",notes = "分页查询")
    @PostMapping//分页查询
    public PageList<User> list(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }

    @PostMapping("/register/phone")
    public AjaxResult register(UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return AjaxResult.me();
        } catch (RuntimeException e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("注册失败"+e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统错误");
        }
    }
}
